﻿using System;
using System.Web;
using WI.CandidateManager.Common.Data.Entities;
using WI.CandidateManager.Common.Logging;
using WI.CandidateManager.DataAccess.Contexts.CacheContext;
using WI.CandidateManager.DataAccess.Contexts.SessionContext;

namespace WI.CandidateManager.Business.Objects
{
    /// <summary>
    /// Base Business Object class
    /// </summary>
    public abstract class BOBase
    {
        #region Properties
        /// <summary>
        /// Instance of Context object for working with DB
        /// </summary>
        private Lazy<CMDBContextContainer> dataContext;
        protected CMDBContextContainer DataContext
        {
            get
            {
                return dataContext.Value;
            }
        }

        /// <summary>
        /// Instance of HttpContext.Current.Cache for working with cache
        /// </summary>
        private Lazy<CMCache> cache;
        protected CMCache Cache
        {
            get
            {
                return cache.Value;
            }
        }

        /// <summary>
        /// Instance of HttpContext.Current.Session for working with session
        /// </summary>
        private Lazy<CMSession> session;
        protected CMSession Session
        {
            get
            {
                return session.Value;
            }
        }

        /// <summary>
        /// Instance of Logger(Log4Net) for working with logger
        /// </summary>
        private Lazy<ILogger> logger;
        protected ILogger Logger
        {
            get
            {
                return logger.Value;
            }
        }
        #endregion

        public BOBase ()
	    {
            //We are in a web app, use a request scope
            if (HttpContext.Current != null)
            {
                if ((CMDBContextContainer)HttpContext.Current.Items["dataContext"] == null)
                {
                    dataContext = new Lazy<CMDBContextContainer>();
                    HttpContext.Current.Items.Add("dataContext", dataContext.Value);
                }
                else
                {
                    dataContext = new Lazy<CMDBContextContainer>(() => (CMDBContextContainer)HttpContext.Current.Items["dataContext"]);
                }
            }
            else
            {
                //If this is not a web app then just create a datacontext
                //which will have the same lifespan as this object
                if (dataContext == null)
                {
                    dataContext = new Lazy<CMDBContextContainer>();
                }
            }

            cache = new Lazy<CMCache>(true);
            session = new Lazy<CMSession>(true);
            logger = new Lazy<ILogger>(()=>LoggerManager.CreateLogger(this.GetType()));
	    }
    }
}
